﻿using CKS.Core.Framework;
using CKS.PLC.Action.Subscription.OP080;
using FreeSql;
using Infrastructure;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using ZR.Model.Models.ProductionControl;
using ZR.Service.IService.ProductionControl;

namespace CKS.PLC.Action.Subscription.OP80
{
    /// <summary>
    /// 动作编号1
    /// 拆模具，存储拆模具结果，并反馈工装使用次数
    /// </summary>
    public class DB3021_Work01Action : OP80ActionBase
    {
        
        public DB3021_Work01Action(DecodeValue _value) : base(_value)
        {
           
        }


        public override string GetBindContent(CksVirtualColumn column)
        {
            if(column.ColumnName == "CoverCode")
            {
                int fixtureId = Value.GetLinkData(1).ToInt(); //夹具编号
                var fixture = conn.Select<CksFixtureinfo>().Where(a => a.FixtureId == fixtureId).First();
                if (fixture != null)
                    return fixture.CoverCode; //返回夹具绑定的盖板码
            }
            return string.Empty;
        }

        //保存成功后对模具次数做增加，如果验证失败，写入
        public override AfterSaveResult AfterSaved(SaveArg e)
        {
            bool ageError = false;
            int fixtureId = Value.GetLinkData(1).ToInt(); //夹具编号
            var fixture = conn.Select<CksFixtureinfo>().Where(a => a.FixtureId == fixtureId).First();
            var ageErrorPos = Value.GetPosition(ReplyPos.BlockDb, ReplyPos.ActionId, 2);
            EventBus.AddLog($"OP80保存数据:FixtureId:{e.RowData["FixtureId"]},FlatnessCheckResult:{e.RowData["FlatnessCheckResult"]},Flatness:{e.RowData["Flatness"]}");

            if(fixture == null)
            {
                fixture = new CksFixtureinfo();
                fixture.FixtureId = fixtureId;
                fixture.MaxUsageCount = 200;
                conn.Insert<CksFixtureinfo>(fixture).ExecuteAffrows();
                fixture = conn.Select<CksFixtureinfo>().Where(a => a.FixtureId == fixtureId).First();
            }


            if (fixture != null)
            {
                var dict = new Dictionary<string, object>();
                dict["Id"] = e.InsertIdentityId;
                dict["CoverCode"] = fixture.CoverCode;
                UpdateDynamicTableData(e.TableInfo, dict);
                //拆完模具，所以需要清空模具状态
                fixture.Status = 0;
                fixture.UpdateTime = DateTime.Now;
                fixture.CellId = 0;
                fixture.ShelfId = 0;
                fixture.BottomPlateCode = string.Empty;
                fixture.CoverCode = string.Empty;

                fixture.UsageCount++;
                if (fixture.UsageCount > fixture.MaxUsageCount)
                    ageError = true;
                conn.Update<CksFixtureinfo>().SetSource(fixture).ExecuteAffrows();

            }
            if (ageError)
            {
                AckWriteInt16(ageErrorPos, 1); //次数超过200次提醒
            }
            else
            {
                AckWriteInt16(ageErrorPos, 0); //复位
            }
            //更新料架信息，重置当前夹具占用的位置
            ResetShelfCell(fixtureId);
            return base.AfterSaved(e);
        }



        /// <summary>
        /// 该方法不执行，仅作备份用
        /// </summary>
        public  void ExecuteOld()
        {
            var replayDB = 3020;
            var replayAction = 10;
            var result = Value.Value.ToInt();
            
            var replayPos = Value.GetPosition(replayDB, replayAction, 1);
            var ageErrorPos = Value.GetPosition(replayDB, replayAction, 2);
            if (result == 1)
            {

                int fixtureId = Value.GetLinkData(1).ToInt(); //夹具编号
                int FlatnessCheckResult = Value.GetLinkData(2).ToInt();//平面度检测结果
                decimal Flatness = Value.GetLinkData(3).ToDecimal(); //平面度
                //更新料架信息，重置当前夹具占用的位置
                ResetShelfCell(fixtureId);

                //如果夹具信息不存在，创建夹具，
                var fixture = conn.Select<CksFixtureinfo>().Where(a => a.FixtureId == fixtureId).First();
                if(fixture == null)
                {
                    fixture = new CksFixtureinfo();
                    fixture.FixtureId = fixtureId;
                    fixture.MaxUsageCount = 200;
                    conn.Insert<CksFixtureinfo>(fixture).ExecuteAffrows();
                    
                }
                //夹具是从上个工位流过来，应该有盖板码。
                var dcOp80Record = new DcOp80Record();
                dcOp80Record.CoverCode = fixture.CoverCode;
                dcOp80Record.FixtureId = fixtureId;
                dcOp80Record.FlatnessCheckResult = FlatnessCheckResult;
                dcOp80Record.Flatness = Flatness;



                dcOp80Record.MoldRemovalTime= dcOp80Record.UpdateTime = DateTime.Now;
               
                conn.Insert(dcOp80Record).ExecuteAffrows();

                bool ageError = false;
                fixture.Status = 0;
                fixture.UpdateTime = DateTime.Now;
                fixture.CellId = 0;
                fixture.ShelfId = 0;

                fixture.UsageCount++;
                if (fixture.UsageCount > fixture.MaxUsageCount)
                    ageError = true;
                conn.Update<CksFixtureinfo>().SetSource(fixture).ExecuteAffrows();
                if (ageError)
                {
                    AckWriteInt16(ageErrorPos, 1); //次数超过200次提醒
                }

                //



                
                AckWriteInt16(replayPos, 1);
                EventBus.AddLog($"OP80请求保存-拆模 夹具编号:{fixtureId}");
            }
            else
            {
                AckWriteInt16(ageErrorPos, 0);
                AckWriteInt16(replayPos, 0);
             
                EventBus.AddLog($"OP80请求保存-拆模具结果-信号重置");
            }
        }
    }
}
